package com.nexfra.vocsys.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.nexfra.vocsys.common.domain.AttachFile;
import com.nexfra.vocsys.common.domain.User;
import com.nexfra.vocsys.common.service.CommonService;
import com.nexfra.vocsys.common.utils.SessionUtil;

@Controller
public class CommonController {

	private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	CommonService commonService;
	
	/**
	 * 메인페이지
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/main")
	public String main(ModelMap model) {
		return "/main";
	}

	/**
	 * 로그인 처리.
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/main/mainframe")
	public String login(@RequestParam Map<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {
		logger.info("requestParam:"+params.toString());
		HttpSession session = request.getSession();
		
		Locale locale = null;
		String localeValue = params.get("rdoLocale")==null 
			|| "".equals(params.get("rdoLocale"))?"ko":params.get("rdoLocale");
		if ("ko".equals(localeValue)) {
			locale = Locale.KOREAN;
		} else if ("en".equals(localeValue)) {
			locale = Locale.ENGLISH;
		}
		
		logger.info("ModelMap:"+model.toString());
		model.addAttribute("params", params);
		logger.info("returnModelMapl:"+model.toString());
		
		/** 세션에 로케일,유저정보 세팅 */
		session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);

//@TODO userinfo를 DB에서 가져온다.		
		User user = new User();
		user.setComId("HANABANK");
		user.setUserId(params.get("user_id"));
		user.setUserName("");
		user.setUserDeptId("");
		user.setUserDeptName("");
		session.setAttribute("userInfo", user);
		logger.info("userInfo:"+user);
		logger.info("userInfo.getUserId:"+user.getUserId());
		
		/** 메뉴정보 조회 */
		HashMap<String, String> sqlParams = new HashMap<String, String>();
		sqlParams.put("USER_ID", params.get("user_id"));
		
		List<Map<String,Object>> topMenuList = commonService.getTopMenuList(sqlParams); // TOP메뉴 조회
		String firstMenuId = "";
		// 최초 Menu ID(2레벨)에 해당하는 하위 노드를 검색한다.
		if(topMenuList != null && topMenuList.size() > 0) { 
			Map<String,Object> item = topMenuList.get(1);
			firstMenuId = (String)item.get("MENU_ID");
			sqlParams.put("MENU_ID", (String)item.get("MENU_ID"));
		}
		List<Map<String,Object>> menuList = commonService.getLeftMenuList(sqlParams);
		session.setAttribute("menuId", firstMenuId); // 메뉴ID
		
		/** 개인화정보 조회 */
		// 일반정보
		sqlParams.put("GROUP_CODE", "GENERAL");
		sqlParams.put("KEY1", "GENERAL");
		List<Map<String,Object>> generalConfig = commonService.getPsersonalConfig(sqlParams);
		session.setAttribute("genaralConfig", generalConfig);
		logger.info("genaralConfig:"+generalConfig);
		
		// 그리드정보
		sqlParams.put("GROUP_CODE", "GRID");
		sqlParams.put("KEY1", firstMenuId);
		List<Map<String,Object>> gridConfig = commonService.getPsersonalConfig(sqlParams);
		session.removeAttribute("gridInfo");
		Map<String,String> gridMap = new HashMap<String,String>();
		for(int i=0; i< gridConfig.size(); i++) {
			Map<String,Object> item = gridConfig.get(i);
			gridMap.put((String)item.get("KEY2")+"_PERM", (String)item.get("VALUE1")); // 그리드id, permulation설정값
			gridMap.put((String)item.get("KEY2")+"_COLMODEL", (String)item.get("VALUE2")); // 그리드id, colMoel설정값
		}
		session.setAttribute("gridInfo", gridMap);
		logger.info("gridInfo:"+gridMap);
		
		// 메뉴정보를 JSON 문자열로 변환
		ObjectMapper om = new ObjectMapper();
        String menuJsonStr = om.writeValueAsString(menuList);
		
		logger.info("topMenuList:"+topMenuList);
		logger.info("menuList:"+menuList);
		logger.info("menuJsonStr:"+menuJsonStr);
		model.addAttribute("topMenuList", topMenuList);
		model.addAttribute("menuList", menuList);
		model.addAttribute("menuJsonStr", menuJsonStr);
		
		return "/main/mainframe";
	}	

	/**
	 * 그리드 항목관리 저장
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/main/savePersonalConfig")
	public String savePersonalConfig(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {
		logger.info("requestParam:"+params.toString());

		HttpSession session = request.getSession();
		params.put("KEY1", (String)session.getAttribute("menuId"));
		params.put("USER_ID", ((User)session.getAttribute("userInfo")).getUserId());

		commonService.savePersonalConfig(params);
		return "";
	}	
	
	
	/**
	 * Left메뉴를 조회한다. 
	 * 
	 * @param model
	 * @return
	 */ 
	@RequestMapping(value = "/main/listLeftMenu.json")
	@ResponseBody
	public List<Map<String,Object>> getLeftMenuList(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {

		params.put("USER_ID", ((User)request.getSession().getAttribute("userInfo")).getUserId());
		logger.info("params:"+params);	
		
		// Left메뉴 조회
		List<Map<String,Object>> list = commonService.getLeftMenuList(params);
		logger.info("list"+list);
		
		return list;
	}

	/**
	 * 공통코드를 조회한다.
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/common/selectCommonCode")
	@ResponseBody
	public List<Map<String,Object>> selectCommonCode(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {	
		
		params.put("lang", SessionUtil.getLang(request));
		params.put("com_id", SessionUtil.getComId(request));
		logger.info("params:"+params);
		
		// Left메뉴 조회
		List<Map<String,Object>> list = commonService.selectCommonCode(params);
		logger.info("list"+list);
		
		return list;
	}

	/**
	 * 첨부파일을 조회한다.
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/common/selectAttachFile")
	@ResponseBody
	public List<AttachFile> selectAttachFile(@RequestParam HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {	
		
		params.put("com_id", SessionUtil.getComId(request));
		logger.info("params:"+params);
		
		// Left메뉴 조회
		//List<Map<String,Object>> list = commonService.selectAttachFile(params);
		List<AttachFile> list = commonService.selectAttachFile(params);
		logger.info("list"+list);
		
		return list;
	}	
	
	/**
	 * return view 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/common/sessionRedirect")
	public String sessionRedirectViewPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) {		
		return "/common/sessionRedirect";
	}	
	
	/**
	 * return view 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{moduleId}/{pageId}")
	public String viewPage(@PathVariable("moduleId") String moduleId,
			@PathVariable("pageId") String pageId, 
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {		
		
		HttpSession session = request.getSession();
		User userInfo = (User)session.getAttribute("userInfo");
		
		/*if(userInfo == null) { // 세션정보가 없을 경우 로긴페이지로 이동
			return "redirect:/main";
		}*/
		  
		// 메뉴ID
		session.setAttribute("menuId", pageId); // 메뉴ID
		
		// 그리드정보
		HashMap<String,String> sqlParams = new HashMap<String,String>();
		sqlParams.put("USER_ID", userInfo.getUserId());
		sqlParams.put("GROUP_CODE", "GRID");
		sqlParams.put("KEY1", pageId);
		List<Map<String,Object>> gridConfig = commonService.getPsersonalConfig(sqlParams);
		
		Map<String,Map<String,String>> gridMap = new HashMap<String,Map<String,String>>();
		Map<String,String> map = null;
		for(int i=0; i< gridConfig.size(); i++) {
			Map<String,Object> item = gridConfig.get(i);
						
			map = new HashMap<String,String>();
			map.put("COLNAMES", (String)item.get("VALUE1")); // colNames설정값
			map.put("COLMODEL", (String)item.get("VALUE2")); // colMoel설정값
			map.put("PERMULATION", (String)item.get("VALUE3")); // permulation설정값
			
			gridMap.put((String)item.get("KEY2"), map); // key2: 그리드id
		}		
		model.addAttribute("gridConfig", gridMap);
		
		return "/"+moduleId+"/"+pageId;
	}	
	
}